package listthree.web;

import listthree.domain.User;
import listthree.service.UserService;
import listthree.service.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2020/6/18 16:44
 * 表示层的控制器Servlet
 * 作用：
 *   1、需要的话，获取请求参数
 *   2、需要的话，将参数封装
 *   3、调用service层相应的方法完成具体的功能（可能需要传递参数）
 *   4，需要的话，将结果保存在域对象（供视图jsp展示数据）
 *   5、转发或重定向到另一jsp/servlet
 **/
@WebServlet("/addUser")
public class AddUser extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*1、设置请求编码
          2、获取所有请求参数
          3、将请求参数封装到user对象
          4、调用service层返回完成添加用户
          5、根据返回值决定：
           转发到add.jsp或重定向userList
         */
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user= new User();
        try {
            /*自动将map封装成user对象*/
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        UserService service = new UserServiceImpl();
        int i = service.addUser(user);
        if (i>0){
            /*添加成功：看到最新数据，重定向到userList*/
            response.sendRedirect(request.getContextPath()+"/userList");
        }else if (i==0){
            /*添加失败:保存提示信息到request域，转发到add.jsp*/
            request.setAttribute("add_error","添加失败");
            request.getRequestDispatcher("/listthree/add.jsp").forward(request,response);
        }else{
            /*用户名重复：保存提示信息到request域，转发到add.jsp*/
            request.setAttribute("add_error","用户名不能重复");
            request.getRequestDispatcher("/listthree/add.jsp").forward(request,response);
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
